let charts = {};

//入口预备函数
$(function () {
    //初始化时间日期
    initClock();

    getToken();
    // ec01_circle_getMemberLevel_d();
    // ec02_map_airLines_a();
    ec03_line_abnormalFlight_d();
});

//加载数据
function loadData() {
    getMyDate();

    getIncome('income', ['income_with_charter', 'site_income_with_charter', 'hour_income_with_charter']); //昨日收入，座公里收入，小时收入
    getIncomeMon('income_mon', ['mon_income_with_charter']); //月累计收入
    getProfit1('profit1', ['all_profit', 'site_mul_cost', 'hour_cost']); //昨日利润，座公里成本，小时成本
    getProfit2('profit2', ['all_cost']); //月累计成本
    getCus('cus', ['cus_cnt']); //昨日旅客量
    getVip('vip', ['vip_num']); //昨日旅客量VIP
    getWgt('wgt', ['wgt']); //昨日货运量
    getMemberLevel('member_level', ['wgt']); //旅客级别

    getMapData('map', ['cus_site_ratio', 'avg_pri_with_charter']); //地图上的数据
    getSafe('safe', ['fly_days', 'act_fly_hour', 'flight_move_cnt']); //安全分析

    getFoc1('foc1', ['TOTAL_COUNT', 'FLIGHTED_COUNT', 'PLAN_FLIGHT_COUNT']); //今日计划，已执行，应执行
    getFoc3('foc3', ['act_fly_hour', 'daily_use_ratio']); //昨日飞行时间，昨日利用率
    getFoc2('foc2', ['NORMAL_RATE', 'BF_COUNT', 'CANCEL_COUNT', 'DELAY_COUNT']); //当前航班正常率、备降、取消、延误
    getOil('oil', ['ECONOMY_FUEL', 'fuel_cost', 'PRICE', 'used_Fuel','USED_FUEL_HOUR']); //当前航班正常率、备降、取消、延误
}

/**
 * jquery get请求的公共选项
 * @param sqlCode 用于拼接sql语句的标识代码
 * @param ids 要绑数的dom元素id们
 * @return {{url: string, data: {dataType: string, params: string}, beforeSend: beforeSend, success: success}}
 */
function getJqOpt(sqlCode, ids) {
    return {
        url: clientUrl,
        data: {
            dataType: 'hl_qdhk_yyfxpt_' + sqlCode,
            params: `dataDt::${yesterdayDate}`
        },
        dataType: 'json',
        beforeSend: function (request) {
            setHeader(request);
        },
        success: function (data) {
            jqAjaxSuccess(data, ids);
        }
    }
}

/**
 * 绑数
 * @param data ajax返回的数据
 * @param ids 要绑数的dom元素id们
 */
function jqAjaxSuccess(data, ids) {
    ids.forEach(function (id) {
        $("#" + id).text(data.data.qdhk[0][id])
    });
}

// 昨日收入，座公里收入，小时收入
function getIncome(sqlCode, ids) {
    $.get($.extend(true, getJqOpt(sqlCode, ids), {}));
}

// 月累计收入
function getIncomeMon(sqlCode, ids) {
    $.get($.extend(true, getJqOpt(sqlCode, ids), {}));
}

// 昨日利润，座公里成本，小时成本
function getProfit1(sqlCode, ids) {
    $.get($.extend(true, getJqOpt(sqlCode, ids), {}));
}

// 月累计成本
function getProfit2(sqlCode, ids) {
    $.get($.extend(true, getJqOpt(sqlCode, ids), {}));
}

// 昨日旅客量
function getCus(sqlCode, ids) {
    $.get($.extend(true, getJqOpt(sqlCode, ids), {}));
}

// 昨日旅客VIP
function getVip(sqlCode, ids) {
    $.get($.extend(true, getJqOpt(sqlCode, ids), {}));
}

//旅客级别
function getMemberLevel(sqlCode) {
    $.get($.extend(true, getJqOpt(sqlCode), {
        success: function (data) {
            let seriesData = [];
            data.data.qdhk.forEach(function (item) {
                seriesData.push({
                    name: item.member_level,
                    value: parseInt(item.cus_cnt),
                })
            });
            ec01_circle_getMemberLevel_d(seriesData);
        }
    }));
}

//旅客级别 环形图
function ec01_circle_getMemberLevel_d(seriesData) {
    let chart = echarts.init($("#ec01_circle_passengerLevel")[0]);
    charts.ec01_circle_passengerLevel = chart;
    chart.setOption(com_circle);
    chart.setOption({
        title: {
            text: '旅客级别',
            textStyle: {
                color: '#fff',
                fontSize: 16 * bodyScale
            },
            x: 'center',
            y: 'bottom'
        },
        series: [{
            startAngle: 0,
            center: ['50%', '45%'],
            label: {
                height: 60 * bodyScale,
                formatter: '{b}:{c}',
                fontSize: 18 * bodyScale
            },
            labelLine: {length: 45 * bodyScale},
            /*
                                data: [
                                    {name: '金卡', value: 10},
                                    {name: '银卡', value: 60},
                                    {name: '普卡', value: 8000},
                                    {name: '白金卡', value: 2}
                                ]
            */
            data: seriesData
        }].map(function (item, index) {
            // .extend里面加上空的对象{}可以让合并时不改变参与的每个对象，否则com_pieSeries会被改变
            return $.extend(true, {}, com_circleSeries, item);
        })
    })
}

// 昨日货运量
function getWgt(sqlCode, ids) {
    $.get($.extend(true, getJqOpt(sqlCode, ids), {}));
}

// 地图上的数据
function getMapData(sqlCode, ids) {
    $.get($.extend(true, getJqOpt(sqlCode, ids), {
        success:function (data) {
            jqAjaxSuccess(data, ids);
            $("#cus_site_ratio").str2NumFixed(2,2)

        }
        })
    );
}


// 安全
function getSafe(sqlCode, ids) {
    $.get($.extend(true, getJqOpt(sqlCode, ids), {
        success: function (data) {
            jqAjaxSuccess(data, ids);
            $("#act_fly_hour").str2NumFixed(0)
        }
    }));
}

ec02_map_airLines_d();

function ec02_map_airLines_d() {
    let chart = echarts.init($("#ec02_map_airLines")[0]);
    charts.ec02_map_airLines = chart;
    chart.showLoading();

    $.get('../assets/data/Asia.json', function (mapJson) {
        chart.hideLoading();
        echarts.registerMap('Asia', mapJson, {});
        //参考案例：http://gallery.echartsjs.com/editor.html?c=xBkrP1lbqG

        let toPoints = ['北京', '上海', '广州', '深圳', '长春', '大连', '拉萨', '乌鲁木齐', '济南', '西安', '南昌', '杭州'];
        let data = toPoints.map(function (item, index) {
            return [geoCoordMap["青岛"],geoCoordMap["济南"], geoCoordMap[item]]
        });
        let series = [{ // 线条和小飞机
            type: 'lines',
            zlevel: 2,
            // symbol: ['none', 'none'],
            symbolSize: 10,
            polyline:true,
            effect: { //小飞机
                show: true,
                period: 6,
                trailLength: 0,
                symbol: fighter,
                symbolSize: 15,
                color: 'green'
            },
            lineStyle: {
                normal: {
                    color: '#f14a61',
                    width: 1,
                    opacity: 0.6,
                    curveness: 0.2
                }
            },
            data: data
        }, { // 每个地点
            type: 'effectScatter',
            coordinateSystem: 'geo',
            zlevel: 1,
            rippleEffect: {
                brushType: 'stroke'
            },
            label: {
                normal: {
                    show: true,
                    position: 'right',
                    formatter: '{b}'
                }
            },
            symbolSize: function (val) {
                return 5;
            },
            itemStyle: {
                normal: {
                    color: '#f14a61',
                }
            },
            data: toPoints.map(function (item, index) {
                return geoCoordMap[item]
            })
        }];

        let option = {
                tooltip: {
                    trigger: 'item',
                    /*formatter: function (params, ticket, callback) {
                        console.log(params);
                        if (params.seriesType === "effectScatter") {
                            return params.data.value;
                        } else if (params.seriesType === "lines") {
                            return params.data.fromName + ">" + params.data.toName;
                        } else {
                            return params.name;
                        }
                    }*/
                },
                geo: {
                    map: 'Asia',
                    //控制台获取当前的位置和缩放比
                    //charts[0].getOption().geo[0].center
                    //charts[0].getOption().geo[0].zoom
                    center: [104.28237877726374, 38.24438844766027],
                    zoom: 1.24184264611831,
                    roam: true,
                    itemStyle: {
                        areaColor: '#b3eefe',
                        borderColor: '#407cd4'
                    },
                    emphasis: {
                        label: {color: '#fff'},
                        itemStyle: {areaColor: '#67BEFE'},
                    },
                },
                series: series
            }
        ;
        chart.setOption(option);
    });
}

// 今日计划，已执行，应执行
function getFoc1(sqlCode, ids) {
    $.get($.extend(true, getJqOpt(sqlCode, ids), {
        data: {
            params: `dataDt::${todayDate}`
        },
    }));
}

// 昨日飞行时间，昨日利用率
function getFoc3(sqlCode, ids) {
    $.get($.extend(true, getJqOpt(sqlCode, ids), {
        success: function (data) {
            ids.forEach(function (id) {
                if (id === 'act_fly_hour') {
                    $("#foc3_" + id).text(data.data.qdhk[0][id])
                } else {
                    $("#" + id).text(data.data.qdhk[0][id])
                }
            });
            $("#foc3_act_fly_hour, #daily_use_ratio").str2NumFixed(0)
        }
    }));
}

// 当前航班正常率、备降、取消、延误
function getFoc2(sqlCode, ids) {
    $.get($.extend(true, getJqOpt(sqlCode, ids), {
        data: {
            params: `dataDt::${todayDate}`
        },
        success: function (data) {
            ids.forEach(function (id) {
                    $("#" + id).text(data.data.qdhk[0][id])
            });
            $("#NORMAL_RATE").str2NumFixed(0,2,'%')
        }
    }));
}

// 昨日油量统计
function getOil(sqlCode, ids) {
    $.get($.extend(true, getJqOpt(sqlCode, ids), {
        /*data: {
            params: `dataDt::20180929`
        },*/
    }));
}


function ec03_line_abnormalFlight_d() {
    let chart = echarts.init($("#ec03_line_abnormalFlight")[0]);
    charts.ec03_line_abnormalFlight = chart;
    chart.setOption(com_line);
    chart.setOption({
        grid: {
            left: '20%',
            top: '17%',
            bottom: '16%'
        },
        xAxis: {
            data: [1, 2, 3, 4, 5, 6, 7],
        },
        yAxis: {
            axisLabel: {
                formatter: function (value, index) {
                    return value.toFixed(2) + '%'
                }
            }
        },
        tooltip: {
            show: true,
            formatter: function (param) {
                // console.log(param)
                return '周' + '一二三四五六日'.split('')[parseInt(param[0].axisValue) - 1] + '</br>'
                    + param[0].seriesName + ': ' + param[0].value + '%</br>'
                    + param[1].seriesName + ': ' + param[1].value
            }
        },
        series: [{
            name: '公司原有占比',
            data: [6.62, 8.23, 10.80, 9.12, 9.90, 6.54, 8.63]
        }, {
            name: '限制',
            data: [8, 8, 8, 8, 8, 8, 8]
        }].map(function (item, index) {
            return $.extend(true, {}, com_lineSeries, item);
        })
    })
}

//获取天气情况
function getWeather(currTime) {
    // 官方文档 http://www.heweather.com/douments/api/s6/weather-forecast
    $.get("https://free-api.heweather.com/s6/weather/forecast?location=青岛&key=7e07c4303b4841e6b1595dca70f9d4a7", function (data) {
        let temperatureTxt = '';
        let daily_forecast = data.HeWeather6[0].daily_forecast[0];
        console.warn(data.HeWeather6[0].status)
        let [code, txt] = ['', ''];
        if ((currTime.getHours() >= 6) && (currTime.getHours() < 18)) {
            code = daily_forecast.cond_code_d;
            txt = daily_forecast.cond_txt_d;
            temperatureTxt = daily_forecast.tmp_min + "℃~" + daily_forecast.tmp_max + "℃";
        } else {
            code = daily_forecast.cond_code_n;
            txt = daily_forecast.cond_txt_n;
            temperatureTxt = daily_forecast.tmp_max + "℃~" + daily_forecast.tmp_min + "℃";
        }
        $("#weather").text(txt);
        $("#temperature").text(temperatureTxt);
        $("#weatherIcon").css('background-image', `url("https://cdn.heweather.com/cond_icon/${code}.png")`);
    })
}

// 获取昨天
function getMyDate() {
    let today = new Date();
    let yesterday = new Date(today - 24 * 3600 * 1000);
    let beforeYesterday = new Date(today - 48 * 3600 * 1000);
    todayDate = '' + today.getFullYear() + (today.getMonth() + 1) + today.getDate();
    yesterdayDate = '' + yesterday.getFullYear() + (yesterday.getMonth() + 1) + yesterday.getDate();
    beforeYesterdayDate = '' + beforeYesterday.getFullYear() + (beforeYesterday.getMonth() + 1) + beforeYesterday.getDate();
}

//初始化时间日期
function initClock() {
    setTimeout(function () {
        let currTime = new Date();
        let [year, mon, date, hour, min, sec, milliSec] = [
            currTime.getFullYear(),
            currTime.getMonth() + 1,
            currTime.getDate(),
            currTime.getHours(),
            currTime.getMinutes(),
            currTime.getSeconds(),
            currTime.getMilliseconds()
        ];
        let time = `${hour}:${min > 9 ? min : "0" + min}:${sec > 9 ? sec : "0" + sec}`;
        let dateStr = `${year}-${mon > 9 ? mon : "0" + mon}-${date > 9 ? date : "0" + date}`;
        $(".time").text(time);
        $(".date").text(dateStr);
        // 调天气预报接口
        if (!hasGetWeather) {
            getWeather(currTime);
            hasGetWeather = true;
        } else {
            if (min % getWeatherPeriod === 0 && sec === 0 && milliSec < 500) {
                getWeather(currTime);
            }
        }

        if (hour === 0 && min === 0 && sec === 0 && milliSec < 500) { //过夜
            getMyDate();
        }
        initClock();
    }, 500)
}

